import {searchJson,delUserid,updateJson} from "/data/userlist.js"
// jquery预加载 
{
    if (sessionStorage.getItem("username") === undefined || sessionStorage.getItem("username") === null || sessionStorage.getItem("username") === "" || sessionStorage.getItem("username") === "null" || sessionStorage.getItem("username") === "undefined") {
        location.href = "/";
    } else {
        //初始化页面的时候将页码数和搜索条件全部制空
        sessionStorage.setItem("page",undefined);
        sessionStorage.setItem("searchText",undefined);
        drawDatas(); 
    }
}
// 点击删除时，获取节点，删除用户信息,为确保点击哪个对应哪个，使用事件委托
$('#user_list').on('click', '.del_btn', async (btnThis) => {
    let tag = confirm('确定删除吗？');
    if (tag) {
        let userid = $(btnThis.target).parents('tr').children().eq(0).html();
        let data = await delUserid({userid});
        alert(data.msg);
        if (data.status === 200) {
            location.reload();
        }
    } else {
        location.reload();
    }

});

// 点击修改时，两个按钮变化,内容框变化
$('#user_list').on('click', '.up_view_btn', (btnThis) => {
    if (!$("button").is(".up_btn")) {
        let tds = $(btnThis.target).parents("tr").children();
        tds.eq(2).html(`<input type="text" id="pwd" value="${tds.eq(2).html()}">`);
        if (tds.eq(3).html() === "管理员") {
            tds.eq(3).html(`
                <select id="isadmin">
                    <option value="1">管理员</option>
                    <option value="0">普通用户</option>
                </select>
            `);
        } else {
            tds.eq(3).html(`
                <select id="isadmin">
                    <option value="0">普通用户</option>
                    <option value="1">管理员</option>
                </select>
            `);
        }
        tds.eq(4).html(`
            <button class="up_btn">确定</button>
            <button class="reset_btn">取消</button>
        `);
    }
});

// 点击取消修改时
$('#user_list').on('click', '.reset_btn', () => {
    location.reload();
});
// 点击确定按钮时
$('#user_list').on('click', '.up_btn', async (btnThis) => {
    let tag = confirm('确定修改吗？');
    if (tag) {
        // 获取ID
        let user = {
            userid: $(btnThis.target).parents('tr').children().eq(0).html()
        }
        // 判断值是否修改了，否则还是默认值
        if ($('#pwd').val() !== $('#pwd').attr('value')) {
            user['pwd'] = $('#pwd').val();
        }
        if ($("#isadmin").val() !== $("#isadmin").children().eq(0).attr("value")) {
            user["isadmin"] = $("#isadmin").val();
        }
        if (Object.keys(user).length > 1) {
            let data = await updateJson(user);
            alert(data.msg);
            if (data.status === 200) {
                location.reload();
            }
        } else {
            alert("暂未修改数据！");
            location.reload();
        }
    } else {
        location.reload();
    }

});


//搜索按钮事件委托
$("#search_btn").on("click",async()=>{
    let key=$("#searchKey").val();
    let value=$("#searcheText").val();
    if(key==="isadmin"){
        if(value==="普通用户")value=0;
        if(value==="管理员")value=1;
    }
    let obj={[key]:value};
    sessionStorage.setItem("page",1);
    sessionStorage.setItem("searchText",JSON.stringify(obj)); 
    drawDatas();
});

//渲染整个数据和分页
async function drawDatas() {
    let page = sessionStorage.getItem("page") * 1;
    let searchText = sessionStorage.getItem("searchText");
    if (searchText === undefined || searchText === "undefined") {
        searchText = JSON.stringify("");
    }
    let data = await searchJson({page,searchText});
    let htmlPageText = "";
    if (data.status === 200) {
        htmlPageText = drawTable(data.datalist);
    } else {
        htmlPageText = `<tr><td colspan="5">暂无数据</td></tr>`;
    }
    $("#user_list").html(htmlPageText);
}



//表格数据与页码数的拼接
function drawTable(datalist) {
    let tableText = ``;
    for (let item of datalist.userlist) {
        tableText += `
            <tr>
                <td>${item.userid}</td>
                <td>${item.username}</td>
                <td>${item.pwd}</td>
                <td>${item.isadmin===1?"管理员":"普通用户"}</td>
                <td>
                    <button class="up_view_btn">修改</button>
                    <button class="del_btn">删除</button>
                </td>
            </tr>
        `;
    }
    //将接口中获取的当前页和总页数，存在本地存储。
    sessionStorage.setItem("page", datalist.page);
    sessionStorage.setItem("pageSum", datalist.pageSum);
    tableText+=`<tr><td colspan="5"><h3>
        <button id="up_page_btn">上一页</button>&nbsp;`;
    for(let i=1;i<=datalist.pageSum;i++){
        tableText+=`
            <a href="javascript:;" class="page_btn">${i}</a>&nbsp;
        `;
    }    
    tableText+=`
       <span class="sum">...总计${datalist.pageSum} 页<button id="down_page_btn">下一页</button>
    </h3></td></tr>`;
    return tableText;
};

$("#user_list").on("click","#up_page_btn",()=>{
    let page=sessionStorage.getItem("page");
    if(page>1){
        sessionStorage.setItem("page",page*1-1);
        drawDatas();
    }
});
$("#user_list").on("click","#down_page_btn",()=>{
    let page=sessionStorage.getItem("page");
    let pageSum=sessionStorage.getItem("pageSum");
    if(page*1<pageSum*1){
        sessionStorage.setItem("page",page*1+1);
        drawDatas();
    }
});
$("#user_list").on("click",".page_btn",(btnThis)=>{
    sessionStorage.setItem("page",$(btnThis.target).text());
    drawDatas();
});